package com.sakiko.audiobook.user.strategy.impl;

import com.sakiko.audiobook.model.user.UserInfo;
import com.sakiko.audiobook.model.user.UserVipService;
import com.sakiko.audiobook.model.user.VipServiceConfig;
import com.sakiko.audiobook.user.mapper.UserInfoMapper;
import com.sakiko.audiobook.user.mapper.UserVipServiceMapper;
import com.sakiko.audiobook.user.mapper.VipServiceConfigMapper;
import com.sakiko.audiobook.user.strategy.ItemTypeStrategy;
import com.sakiko.audiobook.vo.user.UserPaidRecordVo;
import org.joda.time.LocalDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author: sakiko
 * time: 2025/11/9 0:15
 * description: 针对 vip订单的处理
 * todo: 不判断类型怎么找到此实现类
 */
@Service("1003")
public class VipStrategy implements ItemTypeStrategy {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private VipServiceConfigMapper vipServiceConfigMapper;

    @Autowired
    private UserVipServiceMapper userVipServiceMapper;

    @Override
    public void savePaidRecord(UserPaidRecordVo userPaidRecordVo) {
        // 购买 VIP
        UserVipService userVipService = new UserVipService();
        userVipService.setUserId(userPaidRecordVo.getUserId());
        userVipService.setOrderNo(userPaidRecordVo.getOrderNo());
        userVipService.setStartTime(new Date());
        // 设置过期时间
        // case 1: 用户购买 user_info.is_vip = 0; case 2: 用户续期
        UserInfo userInfo = userInfoMapper.selectById(userPaidRecordVo.getUserId());
        // 获取用户 vip购买时长
        Long vipServiceConfigId = userPaidRecordVo.getItemIdList().get(0);
        VipServiceConfig vipServiceConfig = vipServiceConfigMapper.selectById(vipServiceConfigId);
        Integer serviceMonth = vipServiceConfig.getServiceMonth();
        // 创建系统时间
        Date newExpireTime = new Date();
        if (1 == userInfo.getIsVip() && userInfo.getVipExpireTime().after(new Date())) {
            // 是 vip 续期
            newExpireTime = new LocalDateTime(userInfo.getVipExpireTime()).plusMonths(serviceMonth).toDate();
        } else {
            // 不是 vip 购买
            newExpireTime = new LocalDateTime(newExpireTime).plusMonths(serviceMonth).toDate();
        }
        userVipService.setExpireTime(newExpireTime);
        userVipServiceMapper.insert(userVipService);
        // 考虑用户第一次买 设置 user_info.is_vip = 1;
        userInfo.setIsVip(1);
        userInfo.setVipExpireTime(newExpireTime);
        userInfoMapper.updateById(userInfo);
    }
}
